import { useMessage } from '@/hooks/useMessage';
import { ref, Ref, inject } from 'vue';
import { batchTraceSupplierData } from '@/apis/pcf/supplier/supplierList';
import type { GetListBomTreeResult } from '@/apis/pcf/myModel/model/modelDetailModel';
import type { ITraceParams } from '@/apis/pcf/supplier/model/supplierModel';
import { MODEL_DETAIL_ROOT } from '@/views/pcf/myModel/modelDetail/types';
import type { ModelDetailRootProvider } from '@/views/pcf/myModel/modelDetail/types';

export const useBatch = (
  refresh: Fn,
  modelNo: string,
  searchForm: any,
  sourceBomTree: Ref<GetListBomTreeResult[]>
) => {
  const { createMessage, createConfirm } = useMessage();
  const showBatch = ref(false);
  const { modelDetail } = inject(MODEL_DETAIL_ROOT) as ModelDetailRootProvider;
  const batchLoading = ref(false);

  const batchHandleConfirm = () => {
    createConfirm('提示', '是否确认全量追溯BOM？', {
      iconType: 'warning'
    }).then(() => {
      batchHandle();
    });
  };

  /**
   * 批量追溯
   */
  const batchHandle = async () => {
    const results = sourceBomTree.value.map((item: GetListBomTreeResult) => {
      return {
        nodeNo: item.nodeNo,
        num: '1',
        partCode: item.nodeCode,
        partName: item.nodeName,
        dataYear: modelDetail.value?.accountYear,
        unit: item?.unit || (item.dataType == 'ITEM' ? 'pcs' : 'kg'),
        supplierName: item.supplierName,
        remark: item.remark,
        supplierNo: item.supplierNo,
        supplierCode: item.supplierCode,
        supplierUserIds: []
      };
    }) as ITraceParams[];
    try {
      batchLoading.value = true;
      console.log('results', results, modelNo);
      await batchTraceSupplierData(results, modelNo);
      createMessage.success('操作成功！');
      searchForm.searchName = '';
      searchForm.materialCategory = '';
      refresh();
    } finally {
      batchLoading.value = false;
    }
  };

  return {
    batchHandleConfirm,
    batchHandle,
    showBatch,
    batchLoading
  };
};
